﻿namespace PmSoft.Core.Extensions;

/// <summary>
/// 枚举类型的扩展方法
/// </summary>
public static class EnumExtensions
{
	/// <summary>
	/// 获取枚举的显示名称
	/// </summary>
	/// <param name="value">枚举值</param>
	/// <param name="defaultValue">默认值</param>
	/// <returns>枚举的显示名称</returns>
	public static string GetDisplayName(this Enum? value, string defaultValue = "n/a")
	{
		if (value == null)
			return defaultValue;

		string? name = Enum.GetName(value.GetType(), value);
		if (string.IsNullOrEmpty(name))
			return value.ToString();

		var attribute = value?.GetType()?.GetField(name)?.GetCustomAttributes(
			 typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false)
			 .Cast<System.ComponentModel.DataAnnotations.DisplayAttribute>()
			 .FirstOrDefault();

		if (attribute != null)
			return attribute.Name ?? defaultValue;

		return value?.ToString() ?? defaultValue;
	}

	/// <summary>
	/// 获取枚举类型的选项列表
	/// </summary>
	/// <param name="enumType">枚举类型</param>
	/// <returns>枚举类型的选项列表</returns>
	public static IEnumerable<SelectOption> GetEnumOptions(Type enumType)
	{
		if (!enumType.IsEnum) throw new ArgumentException($"{enumType.Name} is not an enum type");
		return Enum.GetValues(enumType).Cast<Enum>().Select(m => new SelectOption { Label = m.GetDisplayName(string.Empty), Value = Convert.ToInt32(m) });
	}

	/// <summary>
	/// 获取枚举类型的选项列表
	/// </summary>
	/// <typeparam name="T">枚举类型</typeparam>
	/// <returns>枚举类型的选项列表</returns>
	public static IEnumerable<SelectOption> GetEnumOptions<T>() where T : struct, Enum
	{
		return Enum.GetValues<T>().Select(m => new SelectOption { Label = m.GetDisplayName(""), Value = Convert.ToInt32(m) });
	}
}

/// <summary>
/// 表示一个选择项
/// </summary>
public class SelectOption
{
	/// <summary>
	/// 选项的值
	/// </summary>
	public int Value { get; set; }

	/// <summary>
	/// 选项的标签
	/// </summary>
	public string Label { get; set; }
}

